<template>
    <div class="e-form">
        <BillTop title="租赁计划变更详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ formData.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更编号：">
                                            <span>{{ formData.changeBillNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更日期：">
                                            <span>{{ formData.billDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>{{ formData.currency }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="原金额（元）：">
                                            <span>{{ formData.totalCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更后金额（元）：">
                                            <span>{{ formData.changeTotalCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁类型：">
                                            <span>{{formData.leaseType ? leaseTypeList[formData.leaseType].label :''}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更期数：">
                                            <span>{{formData.number}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{ formData.baseCurName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12" v-if="formData.leaseType == '2'">
                                        <el-form-item label="传输财务共享：">
                                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.share)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="租赁说明：">
                                            <span>{{ formData.remarks }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                 <el-row v-if="formData.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="formData.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">计划明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left"></div>
                                <div class="right">
                                    <div class="squarecolor">
                                        <div class="color colorAdd"></div>
                                        <span>新增</span>
                                    </div>
                                    <div class="squarecolor item">
                                        <div class="color colorUpdate"></div>
                                        <span>修改</span>
                                    </div>
                                    <div class="squarecolor">
                                        <div class="color colorDel"></div>
                                        <span>删除</span>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planConfigurationDtlList"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planConfigurationDtlList, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column prop="equipmentName" label="设备名称" min-width="200" show-overflow-tooltip align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column prop="changeTimeUnit" width="200">
                                    <template slot="header">
                                        <div class="tab-header">变更后计时单位<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeQuantity" width="150" align="right">
                                    <template slot="header">
                                        <div class="tab-header">变更后租赁数量<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changePrice" width="200" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后单价（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeEnterExitCost" width="230" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后预计进退场费用（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeServiceTime" width="170">
                                    <template slot="header">
                                        <div class="tab-header">变更后预计使用时间<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeAmount" width="200" align="right">
                                     <template slot="header">
                                        <div class="tab-header">变更后金额（元）<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeEnterDate" width="200">
                                    <template slot="header">
                                        <div class="tab-header">变更后预计进场时间<span class="tab-heade-icon">变</span></div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="changeLeaseType"
                                    width="200"
                                    align="center"
                                >
                                    <template slot="header">
                                        <div class="tab-header">变更后建议租赁方式<span class="tab-heade-icon">变</span></div>
                                    </template>
                                    <template slot-scope="{ row }">
                                        <span>{{ row.changeLeaseType ? tenderForm.find(x=>x.value == row.changeLeaseType).label : ''}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="原租赁单价（元）"
                                    width="150"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="原租赁数量"
                                    width="150"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="原计时单位"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                               <el-table-column
                                    prop="enterExitCost"
                                    label="原预计进退场费（元）"
                                    width="180"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原预计金额（元）"
                                    width="150"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.amount}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="原预计进场时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="serviceTime"
                                    label="原预计使用时间"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="tenderForm"
                                    label="原建议租赁方式"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.tenderForm ? tenderForm.find(x=>x.value == row.tenderForm).label : ''}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilityplan" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="50121"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState"  :state="formData.state" @exas="exas" :founderId="formData.founderId"  :isPrint="formData.state === 1 && formData.state === 2" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, webprintReport, showLoading } from '@/utils/common'
import requestAudit from '@/api/equip/common.js'
import request from '@/api/equip/equipPlan.js'
import count from '@/api/equip/equipPlanCount.js'
import { exas } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            isBatch: false, //是否进入批量操作
            batch: '进入批量管理',
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                'share': '',
                'auditCost': 0,
                'auditTime': '',
                'auditor': '',
                'auditorId': '',
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'baseCurTotalCost': 0,
                'billDate': '',
                'billId': '',
                'billNo': '',
                'changeBillId': '',
                'changeBillNo': '',
                'changeState': 0,
                'changeTotalCost': 0,
                'configurationPlanId': '',
                'configurationPlanNo': '',
                'currency': '',
                'currencyId': '',
                'esaId': '',
                'founderId': '',
                'founderName': '',
                'isExcss': 0,
                'isTemporaryLease': '',
                'leaseType': '2',
                'modifier': '',
                'modifierId': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'number': 0,
                'orgId': '',
                'orgName': '',
                'recorder': '',
                'recorderId': '',
                'remarks': '',
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'rmbSumTotalCost': 0,
                'settleAmount': 0,
                'source': '',
                'state': 0,
                'totalCost': 0,
                'version': 0,
                'workId': ''
            },
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 50121,  //配置计划
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 50121,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            billid: this.$route.query.billid,
            planConfigurationDtlList: [], //计划明细
            delBeforeList: [], //删除前的明细
            planSelect: [], //计划明细选择项
            auditHistoryTable: [],
            currentRow: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            isFontColor: true
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            leaseTypeList: state => state.equip.equipData.leaseTypeList, //租赁类型
            tenderForm: state => state.biddingApplication.dictionaries.tenderForm, //招标方式
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>+x.value === param)
                if(obj !== undefined) {
                    return obj.label
                }
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()  //初始化所有数据
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations([ 'setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        batchOperation () {
            this.isBatch = !this.isBatch
            if(this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.planTable.clearSelection()
            }else{
                this.batch = '进入批量管理'
            }
        },
        //传输财务共享字体颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
        shareFontColor () {
            if(this.formData.share === 0 || this.formData.share === 1) {
                this.isFontColor = true
            }else{
                this.isFontColor = false
            }
        },
        //初始化所有数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //基础信息查询
        getInfo () {
            request.getLeaseBaseInfoChange(this.billid).then(res=>{
                this.formData = res
                this.shareFontColor()
            })
        },
        //计划明细查询
        getPlanList () {
            request.getleaseDetailsChange(this.billid).then(res=>{
                this.planConfigurationDtlList = res
                this.onUpCollect()
            })
        },
        //修改基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updateleaseBaseInfoChange(this.formData).then(()=>{
                    this.verifyTable().then(()=>{
                        request.updateleasePlanChange(this.planConfigurationDtlList).then(()=>{
                            this.getInfo()
                            this.getPlanList()
                            resolve()
                        }).catch(err=>{
                            this.setError('planDetail')
                            reject(err)
                        })
                    }).catch(err=>{
                        this.setError('planDetail')
                        reject(err)
                    })

                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                })
            })
        },
        /*明细 */
        //修改行样式
        tableRowClass ({ row }) {
            if(row.state == -1) {
                if(row.leasePlanDtlId) {
                    return 'red'
                }else{
                    return  'row-hide'
                }
            }else if(row.state == 1) {
                return 'green'
            }else if(row.state == 2) {
                return 'yellow'
            }
            return ''
        },
        //模拟添加一行
        selectEquip () {
            let obj =   {
                'changeServiceTime': null,
                'acceptedQuantity': 0,
                'amount': 0,
                'auditAmount': 0,
                'auditEnterExitCost': 0,
                'auditPrice': 0,
                'auditQuantity': 0,
                'auditUseTime': 0,
                'billId': this.billid,
                'billNo': '',
                'changeAmount': null,
                'changeEnterDate': '',
                'changeEnterExitCost': null,
                'changeFacilityPlanLeaseDtlId': '',
                'changeNewOldRate': null,
                'changePrice': null,
                'changeQuantity': null,
                'changeTimeUnit': '',
                'changeType': 1,
                'enterDate': '',
                'enterExitCost': 0,
                'equipmentId': '',
                'equipmentName': '模拟添加的数据',
                'isUsed': '',
                'leasePlanDtlId': '',
                'mark': true,
                'newOldRate': 0,
                'oldState': 0,
                'oneLevelCategoryId': '',
                'oneLevelCategoryName': '',
                'price': 0,
                'quantity': 0,
                'rentalRemark': '',
                'rentalUnit': '',
                'rmbSumCost': 0,
                'scSumCost': 0,
                'serviceTime': 0,
                'specificationModel': '规格',
                'state': 1,
                'timeUnit': '',
                'unit': ''

            }
            this.planConfigurationDtlList.push(obj)
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            if (row.changeFacilityPlanConfigurationDtlId) {
                if (row.state === 2 || row.state === -1 || row.leasePlanDtlId == '') return
                this.currentRow = row
                this.currentRow.changeType = 2
                this.currentRow.state = 2
            }
        },
        //计算金额 = 金额 = 数量*单价*预计使用时间+预计进退场费
        onAmount  (row) {
            row.changeAmount = count.onChangeLeaseAmount(row.changeQuantity, row.changePrice, row.changeServiceTime,  row.changeEnterExitCost)
            this.onUpCollect()
        },
        //费用合计 = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.changeTotalCost = null
            this.formData.changeTotalCost = count.onChangeLeaseUpCollect(this.planConfigurationDtlList)
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //单个删除计划明细
        handleDelete (row, $index) {
            row.oldState = row.state  //存删除之前的状态
            let length = this.errorMsg.length
            if(row.changeFacilityPlanLeaseDtlId) {
                this.$set(this.planConfigurationDtlList[$index], 'changeType', -1)
                this.$set(this.planConfigurationDtlList[$index], 'state', -1)
                if (length > 0 ) {
                    this.verifyTable()
                }
                this.onUpCollect()
            }else{
                this.planConfigurationDtlList.splice($index, 1)
                this.onUpCollect()
                if (length > 0 ) {
                    this.verifyTable()
                }
            }

        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.delete
                )
            }
        },
        //批量删除计划明细
        delete () {
            this.existDelBeforeList()
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.changeFacilityPlanLeaseDtlId) {
                        this.$set(item, 'changeType', -1)
                        this.$set(item, 'state', -1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planConfigurationDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.planConfigurationDtlList[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlList.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        //取消删除
        cancelDelete () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择删除的数据,请选择!',
                )
            }else{
                this.planSelect.forEach(item=>{
                    if(item.changeFacilityPlanLeaseDtlId !== '' && item.state === -1) {
                        let obj = this.planConfigurationDtlList.find(x=>x.changeFacilityPlanLeaseDtlId === item.changeFacilityPlanLeaseDtlId)
                        obj.state = obj.oldState
                        obj.changeType = obj.oldState
                    }

                })
                this.onUpCollect()
                this.$refs.planTable.clearSelection()
            }
        },
        //存删除之前的计划明细的状态
        existDelBeforeList () {
            this.planSelect.forEach(item=>{
                let obj = this.planConfigurationDtlList.find(x=>x.changeFacilityPlanLeaseDtlId === item.changeFacilityPlanLeaseDtlId)
                obj.oldState = obj.state
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/houseLeasePlanList')
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planConfigurationDtlList.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.changeTimeUnit === null || item.changeTimeUnit === '') {
                            let str = `请选择第 ${index + 1} 行的（变更后计时单位）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeQuantity === null || item.changeQuantity === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后租赁数量）`
                            this.errorMsg.push(str)
                        }
                        if(item.changePrice === null || item.changePrice === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后单价）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeEnterExitCost === null || item.changeEnterExitCost === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计进退场费）`
                            this.errorMsg.push(str)
                        }
                        if(item.changeServiceTime === null || item.changeServiceTime === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计使用时间）`
                            this.errorMsg.push(str)
                        }
                        if( item.changeEnterDate === '') {
                            let str = `请填写第 ${index + 1} 行的（变更后预计进场时间）`
                            this.errorMsg.push(str)
                        }
                    }

                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }

            })

        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo()
            ])
                .then(() => {
                    this.init()
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //删除单据
        deleteBills () {
            request.leaseDelete(this.billid).then(()=>{
                this.$router.go(-1)
            })
        },
        //返回变更历史列表
        handleList () {
            this.$router.push({
                path: '/leasePlanShow',
                query: {
                    billid: this.billid,
                    name: 'changeHistory'
                }
            })
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
            if (arg === 'print') {
                const printData = async ()=>{
                    showLoading()
                    try{
                        const  params =  {
                            'reportTitle': '设备租赁计划单', //报表名
                            'orgName': this.formData.orgName, //单据机构
                            'reportQRUri': '', //报表内容URI
                            'billNo': this.formData.billId, //单据编码
                            'summaryInfoItems': [ //基本信息
                                {
                                    'label': '费用合计',
                                    'value': this.formData.changeTotalCost,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '变更编号',
                                    'value': this.formData.changeBillNo,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '原金额',
                                    'value': this.formData.totalCost,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '变更日期',
                                    'value': this.formData.billDate,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '变更期数',
                                    'value': this.formData.number,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '币种',
                                    'value': this.formData.currency,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '临租',
                                    'value': this.formData.leaseType ? this.leaseTypeList[this.formData.leaseType].label : '',
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '备注信息',
                                    'value': this.formData.remarks,
                                    'isFullRow': false //是否占整行
                                },
                            ],
                            'tables': [ //表格
                                {
                                    'tableTitle': '表名',
                                    'tableContent': {
                                        '序号': 'index',
                                        '设备名称': 'equipmentName',
                                        '规格型号': 'specificationModel',
                                        '单位': 'changeTimeUnit',
                                        '数量': 'changeQuantity',
                                        '租赁单价': 'changePrice',
                                        '金额': 'changeAmount',
                                        // '新旧程度%': '规格型号',
                                        // '计时单位': '规格型号',
                                        '预计使用时间': 'changeServiceTime',
                                        '预计进退场费用': 'changeEnterExitCost',
                                        '预计进场时间': 'changeEnterDate',
                                    },
                                    'tableData': this.planConfigurationDtlList, //表格数据
                                },
                                {
                                    'tableTitle': '审核历史',
                                    'tableContent': {
                                        '审核级次': 'unitName',
                                        '审核人': 'assignUser',
                                        '审核岗位': 'userTitle',
                                        '审核时间': 'completeTime',
                                        '审核意见': 'opinion',
                                    },
                                    'tableData': this.auditHistoryTable, //表格数据
                                }
                            ],
                        }

                        hideLoading()
                        return params
                    }catch(err) {
                        console.log(err)
                        this.clientPop('err', '打印失败')
                        hideLoading()
                    }
                }
                const data = await printData()
                webprintReport(data)
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
    .e-table {
    background: #fff;
}
</style>
